subroutine select_prob_event(lunit,eid,dt)
  use param
  use table_param,only:event_profile
  use table_param,only:n_event_profile
  implicit none
  
  integer,intent(in) :: lunit
  integer,intent(out) :: eid
  real(dbl),intent(out) :: dt

  integer :: i,p1,p2
  real(dbl) :: rn,sum1,sum2
  logical :: ierr

  ! Measure the length
  sum1=0
  do i=1,n_event_profile
     if (event_profile(i)%n_event.gt.0) &
          sum1=sum1+&
          event_profile(i)%n_event*event_profile(i)%rate_const
  end do

  ! Throw a random number
  call random_number(rn)
  rn=rn*sum1

  ! Select the corresponding event
  sum2=0
  ierr=.true.
  do i=1,n_event_profile
     if (event_profile(i)%n_event.gt.0) then
        sum2=sum2+&
             event_profile(i)%n_event*event_profile(i)%rate_const
        if (sum2.gt.rn) then
           ! index for event_profile
           p1=i
           ! index for event_table
           call random_number(rn)
           p2=ceiling(rn*event_profile(i)%n_event)
           ierr=.false.
           exit
        end if
     end if
  end do

  if (ierr) call abnormal_stop("select_prob_event",&
       "critical error..")

  ! Measure the time
  do
     call random_number(rn)
     if (rn.ne.0) exit
  end do
  dt=-log(rn)/sum1

  ! Obtain the index for the event table
  eid=event_profile(p1)%event_list(p2)

  return

end subroutine select_prob_event
